import { defineStore } from "pinia";
import { Dialog, Message, MessageDirection, MessageRole, MessageType, SessionConfig } from "@/types/chat";
import { ref } from "vue";
import { GptVersion } from "@/utils/constants";
import { nanoid } from "nanoid";
import { useAuthStore } from "./useAuthStore";

const authStore = useAuthStore();

export interface ChatSession {
  // 会话ID
  id: number;
  // 对话框体
  dialog: Dialog;
  // 对话消息
  messages: Message[];
  // 会话配置
  config: SessionConfig;
  // 清除会话的索引
  clearContextIndex?: number;
}

function createChatSession(dialog?: {
  avatar?: string;
  title?: string;
}): ChatSession {
  return {
    id: 0,
    dialog: {
      avatar: dialog?.avatar || "https://dev-aigc-res.frippler.cn/common/F0CC5CB0140D11EFBB0E1B73FB878D07.jpg",
      title: dialog?.title || "新的对话",
      count: 0,
      subTitle: "请问有什么需要帮助的吗？",
      timestamp: new Date().getTime(),
    },
    messages: [
      {
        avatar: dialog?.avatar || "https://dev-aigc-res.frippler.cn/common/F0CC5CB0140D11EFBB0E1B73FB878D07.jpg",
        content: "请问有什么需要帮助的吗？",
        message_type: MessageType.Text,
        time: Date.now(),
        direction: MessageDirection.Receive,
        role: MessageRole.system,
        id: nanoid(),
      }
    ],
    clearContextIndex: undefined,
    config: {
      gptVersion: GptVersion.GPT_3_5_TURBO,
    }
  };
}

export const useChatStore = defineStore('chatStore', () => {

  // 会话ID
  const id = ref(0);
  // 会话信息
  const sessions = ref<ChatSession[]>([createChatSession()]);
  // 当前会话
  const currentSessionIndex = ref<number>(0);

  // 开启会话
  function openSession(dialog?: { avatar?: string, title?: string }) {
    const session = createChatSession(dialog);
    id.value = id.value + 1;
    session.id = id.value;

    // 当前会话id
    currentSessionIndex.value = 0;
    sessions.value = [session].concat(sessions.value);
    return session;
  }

  // 选择会话
  function selectSession(index: number) {
    currentSessionIndex.value = index;
  }

  // 删除会话
  function deleteSession(index: number) {
    const count = sessions.value.length;
    // 获取需要删除的session
    const deleteSession = sessions.value[index];
    if (!deleteSession) {
      return;
    }

    const new_sessions = sessions.value.slice();
    new_sessions.splice(index, 1);

    // 删除session
    const currentIndex = currentSessionIndex.value;
    let nextIndex = Math.min(currentIndex - Number(index < currentIndex), new_sessions.length - 1);

    if (count === 1) {
      nextIndex = 0;
      new_sessions.push(createChatSession());
    }

    currentSessionIndex.value = nextIndex;
    sessions.value = new_sessions;
  }


  // 当前会话
  function currentSession() {
    let index = currentSessionIndex.value;
    if (index < 0 || index >= sessions.value.length) {
      index = Math.min(sessions.value.length - 1, Math.max(0, index));
      currentSessionIndex.value = index;
    }

    return sessions.value[index];
  }

  // 发送消息
  async function onSendMessage(newMessage: Message) {
    const session = currentSession();
    updateCurrentSession((session) => {
      session.messages = session.messages.concat(newMessage);
    })

    const activeMessages = session.messages.slice(session.clearContextIndex || 0);
    const messages = formatMessages(activeMessages);
    console.log(messages);

    const botMessage: Message = createNewMessage("", MessageRole.system);
    updateCurrentSession((session) => {
      session.messages = session.messages.concat(botMessage);
    })

    const res = await fetch(`${import.meta.env.VITE_APP_BASE_API}/v1/chatgpt/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*',
        'Authorization': authStore.token
      },
      body: JSON.stringify({
        messages,
        model: session.config.gptVersion,
      })
    })

    const reader = res.body?.getReader();
    if (!reader) {
      return;
    }
    console.log('body==>', res);

    const decoder = new TextDecoder();
    let done = false;
    let accumulatedText  = '';
    while(!done) {
      const readRes = await reader.read();
      done = readRes.done;
      if (readRes.value) {
        const chunk = decoder.decode(readRes.value, { stream: true });
        accumulatedText += chunk;
        updateCurrentSession((session) => {
          const botMsgIndex = session.messages.findIndex(msg => msg.id === botMessage.id);
          if (botMsgIndex > -1) {
              session.messages[botMsgIndex].content = accumulatedText;
          }
        })
      }
    }

    // TODO 填充消息
  }

  // 更新当前会话
  function updateCurrentSession(updater: (session: ChatSession) => void) {
    updater(sessions.value[currentSessionIndex.value]);
  }

  function formatMessages(messages: Message[]) {
    // 如果历史消息超过5，只取最新的3个
    const latestMessages = messages.length > 3 ? messages.slice(-3) : messages; // 获取最新的三个消息，如果 messages 长度小于等于 3，则返回全部消息
    return latestMessages.map(({ content, role }) => ({
      content,
      role,
    }));
  }

  function createNewMessage(value: string, role?: MessageRole) {
    return {
      avatar: role !== MessageRole.user ? "https://dev-aigc-res.frippler.cn/common/F0CC5CB0140D11EFBB0E1B73FB878D07.jpg" : "/role/runny-nose.png",
      content: value,
      time: Date.now(),
      role: role || MessageRole.user,
      id: nanoid(),
      streaming: false,
    } as unknown as Message;
  }


  return {
    id,
    sessions,
    currentSessionIndex,
    openSession,
    selectSession,
    deleteSession,
    currentSession,
    onSendMessage,
    updateCurrentSession,
    createNewMessage,
  };
})